package com.taiyuan.zfmvp.ThreadPoolOperateData.controller;

import com.taiyuan.zfmvp.ThreadPoolOperateData.service.AsyncService;
import com.taiyuan.zfmvp.sharding.model.TestCode;
import com.taiyuan.zfmvp.sharding.model.TestSharding;
import com.taiyuan.zfmvp.sharding.service.TestShardingService;
import com.taiyuan.zfmvp.utils.DateUtil;
import com.taiyuan.zfmvp.utils.MD5Util;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import org.apache.commons.codec.binary.Base64;
import javax.annotation.Resource;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

/**
 * @param
 * @Author: zhoufang@si-tech.com.cn
 * @Descriiption:
 * @Date 2022/1/30
 * @return
 */
@Controller
@RequestMapping("/testInsert")
public class TestInsertController {
    private static final Logger logger = LoggerFactory.getLogger(TestInsertController.class.getName());
    @Resource
    private AsyncService asyncService;

    @Resource
    private TestShardingService testShardingService;

    /**
     * @Author zhoufang@si-tech.com.cn
     * @Description   添加信息 多线程
     * @Date 2022/1/30
     * @Param
     * @Return
     */
    @PostMapping("/addInfo")
    @ResponseBody
    public String addInfo(@RequestBody Map<String, Object> inMap) {

        final CountDownLatch countDownLatch = new CountDownLatch(100000);//倒数计数器
        long start = System.currentTimeMillis();
        try {
            for (int i = 0; i < 100000; i++) {
                asyncService.executeAsync(countDownLatch);
            }
            System.out.println("可以在这里执行批量插入等耗时的事情");
            countDownLatch.await();//阻塞当前线程直到countDownLatch 线程等待变量减少为0
            long end = System.currentTimeMillis();
            logger.info("执行批量插入 =======END，耗时=" + (end-start));
            return "000000";
        } catch (Exception e) {
            e.printStackTrace();
        }finally {

        }
        return "000000";
    }

    /**
     * @Author zhoufang@si-tech.com.cn
     * @Description   添加信息 普通
     * @Date 2022/1/30
     * @Param
     * @Return
     */
    @PostMapping("/addInfoputong")
    @ResponseBody
    public String addInfoputong(@RequestBody Map<String, Object> inMap) {

        try {
            testShardingService.addShardingInfo();
            return "000000";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "000000";
    }

    public static String relaceStr(String oldStr){
        String idcreditOld1 = oldStr.replace("+","-");
        String idcreditOld2 = idcreditOld1.replace("/","_");
        String idcreditNew = idcreditOld2.replace("=","");

        return idcreditNew;
    }

    public static void main(String[] args) throws Exception {
       /* String idcredit = aesEncrypt("412726199807017112","2a38ec8dadf86ec1");
        //System.out.println(idcredit);
        System.out.println(relaceStr(idcredit));
        String str1 = relaceStr(idcredit);

        String str2=Base64.encodeBase64String(str1.getBytes("GBK"));
        //System.out.println(str2);
        System.out.println(relaceStr(str2));*/
       /* DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d1 = new Date();
        Date d2 = df.parse("2023-03-21 08:50:13");
       long diff = d1.getTime() - d2.getTime();//这样得到的差值是微秒级别
        long minutes = diff / (1000 * 60);
        System.out.println(minutes);

        System.out.println(Base64.encodeBase64String("202303201428001".getBytes("UTF-8")));*/
/*

        String orderId = "112323232";
        orderId = orderId.substring(2,orderId.length());
        System.out.println(orderId);

        String[] weekDays = {"7", "1", "2", "3", "4", "5", "6"};
        Calendar calendar=Calendar.getInstance();
        System.out.println(weekDays[calendar.get(Calendar.DAY_OF_WEEK)-1]);
*/

       /* Map<String, String> resultMap = new HashMap<>();
        resultMap.put("2", "b");
        resultMap.put("3", "c");
        resultMap.put("5", "e");
        resultMap.put("1", "a");
        resultMap.put("4", "d");
        resultMap.put("8", "d");
        List<Map.Entry<String,String>> list = new ArrayList<Map.Entry<String,String>>(resultMap.entrySet());
        Collections.sort(list,new Comparator<Map.Entry<String,String>>() {
            //升序排序
            public int compare(Map.Entry<String, String> o1,
                               Map.Entry<String, String> o2) {
                return o1.getKey().compareTo(o2.getKey());
            }

        });
        for(Map.Entry<String,String> map:list){
            System.out.println(map.getKey()+":"+map.getValue());
        }*/


      /* String str = "{\"busiResp\": {\"busiDataResp\": {\"CLOSED\": \"已关闭\"},\"page\": null,\"resCode\": \"000000\",\"resMsg\": \"成功\"},\"resCode\": \"000000\",\"resMsg\": \"成功\" }";

       JSONObject task = JSONObject.fromObject(str);
       String code = (String)task.get("resCode");
        if("000000".equals(code)){
            JSONObject jsonObject =  (JSONObject)task.get("busiResp");
            JSONObject jsonObject2 = (JSONObject)jsonObject.get("busiDataResp");
            System.out.println(jsonObject2.toString());
            if(jsonObject2.toString().contains("SUCCESS")){
                System.out.println("支付成功");
            }else{
                System.out.println("支付失败");
            }
        }*/


        BigDecimal longnum = new BigDecimal(6950l);
        BigDecimal longnum1 = new BigDecimal(100);
        BigDecimal result5 = longnum.divide(longnum1,2,BigDecimal.ROUND_HALF_UP);
        System.out.println(result5);

        Long value = 6950L;
        DecimalFormat ft=new java.text.DecimalFormat("#,##0.00#");
        System.out.println(ft.format(value.doubleValue()/100));

    }



    public static String handleDate(long time) throws Exception{
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(time);
        Date old = sdf.parse(sdf.format(date));
        Date now = sdf.parse(sdf.format(new Date()));
        long oldTime = old.getTime();
        long nowTime = now.getTime();

        long day = (nowTime - oldTime) / (24 * 60 * 60 * 1000);

        if (day < 1) {
            return "today";
        } else if (day == 1) {
            return "yesterday";
        } else {
            return "orther";
        }
    }



    //加密方法 str为传输的值 key取商户私钥字符串的前16位
    public static String aesEncrypt(String str, String key) throws Exception {
        if (str == null || key == null) return null;
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes("GBK"), "AES"));
        byte[] bytes = cipher.doFinal(str.getBytes("GBK"));
        //return new BASE64Encoder().encode(bytes);
        return Base64.encodeBase64String(bytes);
    }

    public static String aesDecrypt(String str, String key) throws Exception {
        if (str == null || key == null) return null;
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), "AES"));
        byte[] bytes = new BASE64Decoder().decodeBuffer(str);
        bytes = cipher.doFinal(bytes);
        return new String(bytes, "utf-8");
    }





}
